package com.zzxx.interceptor;

import com.zzxx.entity.User;
import com.zzxx.entity.UserExample;
import com.zzxx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AutologinInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService service;
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
            String username=null;
            String password=null;
            Cookie[] cookies = req.getCookies();
            if(cookies!=null){
                for(Cookie c:cookies){
                    if(c.getName().equals("username")){
                        username=c.getValue();
                    }
                    if(c.getName().equals("password")){
                        password=c.getValue();
                    }
                }
            }
            if(username!=null&&password!=null){
                try {
                    User user = service.findUser(username, password);
                    req.getSession().setAttribute("loginUser",user);
                }catch (Exception e){
                    Cookie cookie1 = new Cookie("username",username );
                    Cookie cookie2 =new Cookie("password",password);
                    cookie1.setPath(req.getContextPath());
                    cookie2.setPath(req.getContextPath());
                    cookie1.setMaxAge(0);
                    cookie2.setMaxAge(0);
                    resp.addCookie(cookie1);
                    resp.addCookie(cookie2);
                }
            }
        return true;
     }


}
